const express = require('express');
const { createServer } = require('http');
const { Server } = require('socket.io');
const pty = require('node-pty');
const os = require('os');

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"]
  }
});

const shell = os.platform() === 'win32' ? 'powershell.exe' : 'zsh';

io.on('connection', (socket) => {
  console.log('Client connected');

  const term = pty.spawn(shell, [], {
    name: 'xterm-color',
    cols: 80,
    rows: 24,
    cwd: process.env.HOME,
    env: process.env,
  });

  // 處理終端機輸入
  socket.on('input', (data) => {
    term.write(data);
  });

  // 處理終端機大小調整
  socket.on('resize', (size) => {
    term.resize(size.cols, size.rows);
  });

  // 將終端機輸出發送到客戶端
  term.on('data', (data) => {
    socket.emit('output', data);
  });

  socket.on('disconnect', () => {
    console.log('Client disconnected');
    term.kill();
  });
});

// 在開發環境中，Next.js 會處理靜態文件
// 在生產環境中，我們需要提供靜態文件服務
if (process.env.NODE_ENV === 'production') {
  app.use(express.static('out'));
}

const port = process.env.PORT || 4000;
httpServer.listen(port, () => {
  console.log(`Server running on port ${port}`);
}); 